﻿using HeerCards.Helper;
using Native.Sdk.Cqp;
using Native.Sdk.Cqp.EventArgs;
using PCRRPG.Code.EconomySystem;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Code
{
    public class Event_drawCard
    {
        public static void draw(HeerCards.HCPool item, CQGroupMessageEventArgs e)
        {
            item.CostItem = item.CostItem ?? "";
            bool result = true;
            //抽一次
            var card = item.GetCard(1);
            var str = "";
            //初始化回复语句
            if (AppMain.GobalSetting.ReplyMessage == "")
            {
                str = ("恭喜获得了:" + card[0].Card.Name + "\n{Card.Image}");//默认语句
            }
            else
            {
                //设定好的语句，第一次变量替换
                str = CardTextHelper.getText(item, card[0].Level, card[0].Card, AppMain.GobalSetting.ReplyMessage);//自定义的语句
            }

            //判断是否是图片模式
            if (AppMain.GobalSetting.useImage && item.useImage && e.CQApi.IsAllowSendImage)
            {
                var imagepath = "card2\\" + card[0].Card.LocalImagePath;
                if (File.Exists(e.CQApi.AppDirectory.Replace("app\\github.heerheer.card2", "image") + imagepath))
                {
                    //三个条件都满足会替换图片变量
                    //str = App.GobalSetting.ReplyMessage == "" ? "{Card.Image}" : str;
                    str = str.Replace("{Card.Image}", CQApi.CQCode_Image(imagepath).ToString());
                }
                else
                {
                    e.CQLog.Info("图片加载", "找不到图片" + e.CQApi.AppDirectory.Replace("app\\github.heerheer.card2", "image") + imagepath);
                    str = str.Replace("{Card.Image}", "").Trim().TrimEnd('\n');
                }
            }
            else
            {
                //若不满足就不发了
                str = str.Replace("{Card.Image}", "").Trim().TrimEnd('\n');
            }

            result = deal(e, item, card, 1);

            if (result)
                e.FromGroup.SendGroupMessage(str.Replace("{at}", CQApi.CQCode_At(e.FromQQ.Id).ToString()));
            else
                e.FromGroup.SendGroupMessage($"似乎遇到了些什么问题\n有可能是你{((item.CostItem == "") ? "money" : item.CostItem)}不够了".Trim());

            e.Handler = true;
        }

        public static void draw(HeerCards.HCPool item, CQGroupMessageEventArgs e, int times)
        {
            item.CostItem = item.CostItem ?? "";
            bool result = true;
            //抽10次
            var card = item.GetCard(times);
            StringBuilder sb = new StringBuilder();
            //初始化回复语句
            if (AppMain.GobalSetting.TenReplyMessage == "" || AppMain.GobalSetting.TenReplyMessage == null)
            {
                sb.AppendLine("{at}恭喜获得了".Replace("{at}", CQApi.CQCode_At(e.FromQQ.Id).ToString()));
            }
            else
            {
                //设定好的语句，第一次变量替换
                sb.AppendLine(AppMain.GobalSetting.TenReplyMessage.Replace("{at}", CQApi.CQCode_At(e.FromQQ.Id).ToString()));
            }

            var useTenImage = false;
            //判断是否是图片模式
            if (AppMain.GobalSetting.useImage && item.useImage && e.CQApi.IsAllowSendImage)
            {
                useTenImage = true;
                //判断每张图片是否都存在
                foreach (var thecard in card)
                {
                    var imagepath = "card2\\" + thecard.Card.LocalImagePath;
                    if (!File.Exists(e.CQApi.AppDirectory.Replace("app\\github.heerheer.card2", "image") + imagepath))
                    {
                        e.CQLog.Info("图片加载", "找不到图片" + e.CQApi.AppDirectory.Replace("app\\github.heerheer.card2", "image") + imagepath);
                        useTenImage = false;
                        break;
                    }
                }

                //高级版限制已删除

                //接下来开始真正的生成
                if (useTenImage)
                {
                    var path = e.CQApi.AppDirectory.Replace("app\\github.heerheer.card2", "image") + @"card2\";
                    var back = (File.Exists((path + "Background.png"))) ? path + "Background.png" : null;
                    CardImageHelper cardImage = new CardImageHelper(card, path);
                    using (var v = cardImage.createImage(back))
                    {
                        var gr = Guid.NewGuid().ToString();
                        v.Save(path + "temp\\" + gr + ".png");
                        sb.AppendLine(CQApi.CQCode_Image(@"card2\temp\" + gr + ".png").ToString());
                    }
                }
                else
                {
                }
            }
            else
            {
                useTenImage = false;
            }

            if (!useTenImage)
            {
                foreach (var c in card)
                {
                    if (AppMain.GobalSetting.TenReplyMessageCardFormat != null
                        && AppMain.GobalSetting.TenReplyMessageCardFormat != "")
                    {
                        //自定义格式
                        sb.Append(CardTextHelper.getText(item, c.Level, c.Card, AppMain.GobalSetting.TenReplyMessageCardFormat.Replace("{Card.Image}", "")));
                        if (!AppMain.GobalSetting.TenReplyNoReturn)
                        {
                            sb.Append(Environment.NewLine);
                        }
                    }
                    else
                    {
                        //默认格式
                        sb.AppendLine($"[{c.Level.Name}] {c.Card.Name}");
                    }
                }
            }

            result = deal(e, item, card, times);

            if (result)
                e.FromGroup.SendGroupMessage(sb.Replace("{at}", CQApi.CQCode_At(e.FromQQ.Id).ToString()).ToString());
            else
                e.FromGroup.SendGroupMessage($"似乎遇到了些什么问题\n有可能是你{((item.CostItem == "") ? "money" : item.CostItem)}不够了".Trim());

            e.Handler = true;
        }

        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="e"></param>
        /// <param name="item"></param>
        /// <param name="cards"></param>
        /// <param name="times"></param>
        /// <returns></returns>
        private static bool deal(CQGroupMessageEventArgs e, HeerCards.HCPool item, List<HeerCards.PoolGetInfo> cards, int times)
        {
            #region 卡池消耗部分

            var result = true;
            if (AppMain.GobalSetting.saveData)
            {
                result = EconomyOperater.TryDeductMoney(e.FromQQ.Id, e.FromGroup.Id, item.CostItem, item.Cost*times);
            }

            if (result)
            {
                //EconomyOperater.WriteValue(e.FromQQ.Id, e.FromGroup.Id,)

            }
            return result;

            #endregion 卡池消耗部分
        }
    }
}